package com.dkd.sbtz.controller;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;

import com.dkd.common.utils.StringUtils;
import com.dkd.sbtz.domain.vo.BindParentReq;
import com.dkd.sbtz.domain.vo.BindTypeChildrenRequest;
import com.dkd.sbtz.domain.vo.sbtype.SaveTypeRelationsReq;
import com.dkd.sbtz.domain.vo.sbtype.TypeRelationsVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.enums.BusinessType;
import com.dkd.sbtz.domain.Sbtype;
import com.dkd.sbtz.service.ISbtypeService;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.common.core.page.TableDataInfo;

/**
 * 设备类型Controller
 * 
 * @author xzj
 * @date 2025-09-02
 */
@RestController
@RequestMapping("/sbtz/sbtype")
public class SbtypeController extends BaseController
{
    @Autowired
    private ISbtypeService sbtypeService;

    /**
     * 查询设备类型列表
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:list')")
    @GetMapping("/list")
    public TableDataInfo list(Sbtype sbtype)
    {
        startPage();
        List<Sbtype> list = sbtypeService.selectSbtypeList(sbtype);
        return getDataTable(list);
    }

    /**
     * 导出设备类型列表
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:export')")
    @Log(title = "设备类型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Sbtype sbtype)
    {
        List<Sbtype> list = sbtypeService.selectSbtypeList(sbtype);
        ExcelUtil<Sbtype> util = new ExcelUtil<Sbtype>(Sbtype.class);
        util.exportExcel(response, list, "设备类型数据");
    }

    /**
     * 获取设备类型详细信息
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:query')")
    @GetMapping(value = "/{typeCode}")
    public AjaxResult getInfo(@PathVariable("typeCode") String typeCode)
    {
        return success(sbtypeService.selectSbtypeByTypeCode(typeCode));
    }

    /**
     * 新增设备类型
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:add')")
    @Log(title = "设备类型", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Sbtype sbtype)
    {
        return toAjax(sbtypeService.insertSbtype(sbtype));
    }

    /**
     * 修改设备类型
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:edit')")
    @Log(title = "设备类型", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Sbtype sbtype)
    {
        return toAjax(sbtypeService.updateSbtype(sbtype));
    }


    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:edit')")
    @Log(title = "设备类型", businessType = BusinessType.UPDATE)
    @PostMapping("/updateDeviceCount")
    public AjaxResult updateDeviceCount(@RequestBody Sbtype sbtype)
    {
        // 参数校验
        if (sbtype.getTypeCode() == null) {
            return AjaxResult.error("设备类型编码不能为空");
        }
        if (sbtype.getDeviceCount() == null || sbtype.getDeviceCount() < 0) {
            return AjaxResult.error("设备台数不能为空且必须大于等于0");
        }

        return toAjax(sbtypeService.updateDeviceCount(sbtype));
    }

    /**
     * 删除设备类型
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:remove')")
    @Log(title = "设备类型", businessType = BusinessType.DELETE)
	@DeleteMapping("/{typeCodes}")
    public AjaxResult remove(@PathVariable String[] typeCodes)
    {
        return toAjax(sbtypeService.deleteSbtypeByTypeCodes(typeCodes));
    }

    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:bindChildren')")
    @Log(title = "设备类型-绑定下一级", businessType = BusinessType.UPDATE)
    @PutMapping("/edges")
    public AjaxResult bindChildren(@Validated @RequestBody BindTypeChildrenRequest req) {
        // 去重、清洗
        Set<String> uniq = new LinkedHashSet<>();
        for (String c : req.getChildTypes()) {
            if (StringUtils.isNotBlank(c)) uniq.add(c.trim());
        }
        // 过滤掉与父相同的 code（避免自环）
        uniq.remove(req.getParentType());

        int affected = sbtypeService.replaceChildren(req.getParentType(), List.copyOf(uniq));
        return AjaxResult.success().put("affected", affected);
    }


    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:edit')")
    @Log(title = "资产类型父子绑定", businessType = BusinessType.UPDATE)
    @PostMapping("/bindParent")
    public AjaxResult bindParent(@RequestBody @Validated BindParentReq req) {
        sbtypeService.bindParent(req.getChildType(), req.getParentTypes());
        return AjaxResult.success();
    }


    /** 查询某类型的父/子 codes（用于修改弹窗回显） */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:relation:query')")
    @GetMapping("/relation/{typeCode}")
    public AjaxResult getRelations(@PathVariable String typeCode) {
        TypeRelationsVO vo = sbtypeService.getRelations(typeCode);
        return AjaxResult.success(vo);
    }

    /** 一次性保存父/子关系（修改弹窗点击确定后调用） */
    @PreAuthorize("@ss.hasPermi('sbtz:sbtype:relation:save') or @ss.hasPermi('sbtz:sbtype:edit')")
    @Log(title = "设备类型关系", businessType = BusinessType.UPDATE)
    @PostMapping("/relation/save")
    public AjaxResult saveRelations(@RequestBody SaveTypeRelationsReq req) {
        sbtypeService.saveRelations(req);
        return AjaxResult.success();
    }



}
